<?php


namespace app\common\command;

use app\common\model\Goods;
use app\common\model\GoodsSku;
use app\common\model\Order;
use app\common\model\PointsLog;
use app\common\model\Shop;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use think\facade\Db;
use think\facade\Log;

class CancelOrder extends Command
{
    protected function configure()
    {
        // 指令配置
        $this->setName('cancel_order')
            ->setDescription('取消订单');
    }

    protected function execute(Input $input, Output $output)
    {
        /**
         * 当 券  超过7天未使用
         * 进行退款操作
         */
        $startTime = time() - 7 * 24 * 60 * 60;
//        $startTime = time();
        $list = Order::where('create_time', '<', $startTime)
            ->where('goods_shop_id', '<>', 0)
            ->where('pay_status', 1)
            ->where('receive_time', 0)
            ->limit(50)
            ->field('id,refund_status,status,pay_status,user_id,goods_shop_id,price,goods_id,num,sku_id')
            ->select();

        $arr = [];
        $arr1 = [];
        foreach ($list as $k => $v) {
            Db::startTrans();
            try {
                //订单处理
                $v->refund_status = 2;
                $v->status        = 3;
                $v->pay_status    = 3;
                $v->save();
                //店铺积分退还
                //用户记录 增加积分记录
                PointsLog::where('user_id', $v->user_id)
                    ->where('relation_id', $v->id)
                    ->useSoftDelete('delete_time', time())->delete();
                //商家减少积分
                Shop::where('id', $v->goods_shop_id)->dec('points_one', $v->price)->update();

                //销量+1 , 库存-1
                Goods::where('id', $v->goods_id)->inc('total_stock', $v->num)->dec('sales', $v->num)->update();
                GoodsSku::where('id', $v->sku_id)->inc('stock', $v->num)->update();

                Db::commit();
                $arr[] = $v->id;
            } catch (\Exception $e) {
                Db::rollback();
                $arr1[] = $v->id;
                Log::task($v);
                Log::task($e->getMessage() . $e->getTraceAsString());
            }
        }
        $output->writeln('执行结束'.json_encode($arr).'||执行失败'.json_encode($arr1));
    }
}